from google.appengine.ext import webapp
#from google.appengine.ext.webapp import util
import datetime
from django.utils import simplejson
#from ft_utils import *
import logging
from ft_table import FtTable
import dlz_config as dc

FT_USERNAME = 'osu.map@gmail.com'
FT_PASSWORD = 'dlzosumap'

class ProjectHandler(webapp.RequestHandler):
    def get(self):
        self.post()
    def getClients(self):
        '''Get a list of clients for tree control'''
        ft = FtTable(FT_USERNAME, FT_PASSWORD, int(dc.get('DLZ_PROJECT_LIST')['ft_table_id']))
        response = ft.SqlQuery("select client_name , count() as ct from %s group by client_name order by client_name" % ft.tableid)
        results = []
        for r in response:
            results.append({'text': '%(client_name)s(%(ct)s)' % r, 'id': 'client--%s' % r['client_name'], 'cls': 'folder'})
        return results
    
    def queryClients(self):
        '''Get a list of clients'''
        ft = FtTable(FT_USERNAME, FT_PASSWORD, int(dc.get('DLZ_PROJECT_LIST')['ft_table_id']))
        response = ft.SqlQuery("select client_name , count() as ct from %s group by client_name order by client_name" % ft.tableid)
        meta = {"totalProperty": "total", "successProperty": "success", "idProperty": "client_name", "root": "rows", "fields": ["client_name", "ct"]}
        return {'rows': [{'client_name': 'All', 'ct': 1}] + response, 'total': len(response), 'success': True, 'metaData': meta}
    def queryProjects(self, client_name):
        ft = FtTable(FT_USERNAME, FT_PASSWORD, int(dc.get('DLZ_PROJECT_LIST')['ft_table_id']))
        if client_name=='All':
            response = []
        response = ft.SqlQuery("select project_name, project_number from %s where client_name = '%s' ORDER BY project_name" % (ft.tableid, client_name))
        meta = {"totalProperty": "total", "successProperty": "success", "idProperty": "client_name", "root": "rows", "fields": ["project_name","project_number"]}
        return {'rows': [{'project_name': 'All', 'project_number': ''}] + response, 'total': len(response), 'success': True, 'metaData': meta}
    
    def getForms(self, project_number):
        '''get a list of forms filled for the project'''
        ft = FtTable(FT_USERNAME, FT_PASSWORD, int(dc.get('DLZ_COMPACTION_FORM')['ft_table_id']))
        sql = "select * from %s where project_key starts with '%s' order by form_date" % (ft.tableid, project_number)
        
        response = ft.SqlQuery(sql)
        results = []
        
        for r in response:
            node = {'text': r['form_date'], 'id': 'form--%s--%s' % (int(dc.get('DLZ_COMPACTION_JOIN')['ft_table_id']),r['ID']),
                     'cls': 'folder', 'leaf': True}
            
            node['project_name'] = r['project_name']
            node['project_number'] = r['project_number']
            node['date'] = r['form_date']
            
            results.append(node)
        return results
 
    def getProjects(self, client_name):
        '''
        list projects for tree controls
        '''
        ft = FtTable(FT_USERNAME, FT_PASSWORD, int(dc.get('DLZ_PROJECT_LIST')['ft_table_id']))
        response = ft.SqlQuery("select client_name, project_name, project_number from %s where client_name = '%s' ORDER BY project_name" % (ft.tableid, client_name))
        fields = ['project_name', 'project_number']
        results = []
        for r in response:
            results.append({'text': '%(project_name)s(%(project_number)s)' % r, 
                            'id': 'project--%s' % r['project_number'], 'cls': 'folder', 'leaf': True,
                             'project_name': r['project_name'],'project_number': r['project_number'], 'client_name': r['client_name']})
        
        return results
    def post(self):
        node = self.request.get('node')
        if node=='root':
            results = self.getClients()
        elif node.startswith('client'):
            prefix, client_name = node.split('--')
            results = self.getProjects(client_name)
        elif node.startswith('project'):
            prefix, project_number = node.split('--')
            #results = self.getInvoices(project_number)
            results = self.getForms(project_number)
        elif node=='queryclient':
            results = self.queryClients()
        elif node=='queryproject':
            client_name = self.request.get('client_name')
            results = self.queryProjects(client_name)
        self.response.headers["Content-Type"] = "application/json"   
        self.response.out.write(simplejson.dumps(results)) 